package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.StrategyContent;
import cn.wolfcode.trip.base.domain.StrategyDetail;
import cn.wolfcode.trip.base.mapper.StrategyCatalogMapper;
import cn.wolfcode.trip.base.mapper.StrategyContentMapper;
import cn.wolfcode.trip.base.mapper.StrategyDetailMapper;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.IStrategyDetailService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;


@Service
public class StrategyDetailServiceImpl implements IStrategyDetailService {
    @Autowired
    private StrategyDetailMapper strategyDetailMapper;
    @Autowired
    private StrategyContentMapper strategyContentMapper;

    @Override
    public StrategyDetail getDetailById(Long id) {
        return strategyDetailMapper.selectByPrimaryKey(id);
    }

    @Override
    public StrategyContent getContentById(Long id) {
        return strategyContentMapper.selectByPrimaryKey(id);
    }

    @Override
    public Object query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        List<StrategyDetail> list = strategyDetailMapper.selectForList(qo);
        return new PageInfo<>(list);
    }

    @Override
    public void saveOrUpdate(StrategyDetail strategyDetail) {
        //判断是否有序号
        if (strategyDetail.getSequence() == null) {
            //查询  获取该攻略的最大序号
            int max=strategyDetailMapper.selectMaxSequence(strategyDetail.getCatalog().getId());
            //设置序号+1
            strategyDetail.setSequence(max+1);
        }



        //保存攻略文章内容
        //1.获取攻略文章内容
        StrategyContent strategyContent = strategyDetail.getStrategyContent();


        if (strategyDetail.getId()!= null) {


            //更新
            strategyDetailMapper.updateByPrimaryKey(strategyDetail);
            //主键关联
            strategyContent.setId(strategyDetail.getId());
            //更新文章内容
            strategyContentMapper.updateByPrimaryKey(strategyContent);
        }else{
            //保存攻略基本信息
            strategyDetailMapper.insert(strategyDetail);
            //主键关联 不能抽取出来 因为新增时没有id
            strategyContent.setId(strategyDetail.getId());
            //保存攻略文章内容
            strategyContentMapper.insert(strategyContent);
        }


        //判断是否是发布
        if (strategyDetail.getState()== StrategyDetail.STATE_RELEASE) {
            //设置发布时间
            strategyDetail.setReleaseTime(new Date());
            //设置发布时间
            strategyDetailMapper.updateReleaseTime(strategyDetail);

        }




    }
}
